﻿using SecurityAdmin.Web.Models;
using SecurityApi.DataAccess;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.Infrastructure;
using Kendo.Mvc.UI;

namespace SecurityAdmin.Web.Controllers
{
    public class UserRoleController : BaseController
    {
        //
        // GET: /UserRole/

        public ActionResult Index()
        {
           UserRoleViewModel vm = new UserRoleViewModel();
            return View(vm);
        }


        public ActionResult AddUserRole(int roleId)
        {
            int userId = SelectedUser.UserId;
            UserRoleRepository userRoleRepository = new UserRoleRepository();
            userRoleRepository.AddUserRole(userId, roleId);
            return RedirectToAction("RoleManager");
        }


        public ActionResult AjaxGetAvailableRoles(int userId,int applicationId, [DataSourceRequest] DataSourceRequest request)
        {
            SecurityApiEntities context = new SecurityApiEntities();
            RoleRepository roleRepository = new RoleRepository(context);
            IQueryable<Role> roles = roleRepository.GetApplicationRoles(applicationId);

            UserRoleRepository userRoleRepository = new UserRoleRepository(context);
            IQueryable<SecurityApi.Model.UserRole> userRoles = userRoleRepository.GetUserRoles(userId, applicationId);

            var resultList = from a in roles
                             where !(userRoles.Any(entry => entry.RoleId == a.RoleId))
                             select a;

            //UserRoleViewModel vm = new UserRoleViewModel();
            //vm.AvailableRoles = resultList.ToList();
            return Json(resultList.ToDataSourceResult(request));
        }

        public ActionResult AjaxGetAssignedRoles(int userId,int applicationId, [DataSourceRequest] DataSourceRequest request)
        {
            SecurityApiEntities context = new SecurityApiEntities();
            RoleRepository roleRepository = new RoleRepository(context);
            IQueryable<Role> roles = roleRepository.GetApplicationRoles(applicationId);

            UserRoleRepository userRoleRepository = new UserRoleRepository(context);
            IQueryable<SecurityApi.Model.UserRole> userRoles = userRoleRepository.GetUserRoles(userId, applicationId);

            var resultList = from a in roles
                             where (userRoles.Any(entry => entry.RoleId == a.RoleId))
                             select a;

            UserRoleViewModel vm = new UserRoleViewModel();
            return Json(resultList.ToDataSourceResult(request));
        }

        public ActionResult RoleManager()
        {
            return View();
        }

    }
}
